﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using Hotnet.Web.Utility;
using Hotnet.Biz.NSBizCommon;
using Hotnet.Entity;
using Hotnet.Web.MVCExtension;
using Hotnet.Biz.NSBizVideo;
using System.IO;
using Hotnet.Entity.Search;
using Hotnet.Entity.Enum;
using Component.Utilities;
using ZoomImageDemo;

namespace Hotnet.Web.Controllers.Admin
{
	public class AdminVideoController : AdminBaseController
	{
		//
		// GET: /AdminVideo/
		private new const int PAGE_SIZE = 10;
		private BizSourceFrom bizSourceFrom;
		private BizStar bizStar;
		private BizVideo bizVideo;
		private BizVideoXTag bizVideoXTag;
		private BizCastCharacter bizCastCharacter;
		private BizVideoCategory bizVideoCategory;
		private BizVideoList bizVideoList;
		private string videoCoverImageFolder = Hotnet.Biz.Properties.Settings.Default.VideoCoverImageFolder;
		public AdminVideoController(BizSourceFrom bizSourceFrom, BizStar bizStar, BizVideo bizVideo, BizVideoXTag bizVideoXTag, BizCastCharacter bizCastCharacter, BizVideoCategory bizVideoCategory,BizVideoList bizVideoList)
		{
			this.bizVideoList = bizVideoList;
			this.bizSourceFrom = bizSourceFrom;
			this.bizStar = bizStar;
			this.bizVideo = bizVideo;
			this.bizVideoXTag = bizVideoXTag;
			this.bizCastCharacter = bizCastCharacter;
			this.bizVideoCategory = bizVideoCategory;
		}


		public ActionResult Index(int? pageNo,SearchVideoCondition searchObj)
		{
			int totalCount=0;
			searchObj.IsGroup = false;
			VideoCategory category = bizVideoCategory.Get(searchObj.CategoryID.Value);
			ViewListVideo[] list = bizVideo.List(pageNo ?? 0, PAGE_SIZE, out totalCount, searchObj, searchObj.IsPublished);
			ViewData["PaginateHelper"] = PaginateHelper.ConstructPaginate(totalCount, pageNo ?? 0, PAGE_SIZE, "/AdminVideo/Index/", searchObj);
			ViewData["CategoryID"] = searchObj.CategoryID;
			ViewData["CategoryName"] = category.Name;
			ViewData["Videos"] = list;
			return View(list);
		}

		//
		// GET: /AdminVideo/Details/5

		public ActionResult Details(int id)
		{
			return View();
		}

		//
		// GET: /AdminVideo/Create

		public ActionResult Create(int? categoryid)
		{
			ViewData["Title"] = "视频创建";
			ViewData["CategoryID"] = categoryid;
			ViewData["CategoryName"] = bizVideoCategory.Get(categoryid ?? 0).Name;
			InitCreateUpdate(null,null,null);
			return View();
		}

		private void InitCreateUpdate(List<string> selectSourceFrom,List<string> selectStars,List<string> selectDirector)
		{
			var stars = bizStar.List<string>(x => x.StarName, false);
			var sourceFromList=bizSourceFrom.List(EnumSystemCategory.视频);
			var extendAttributes=sourceFromList.Select(x=>x.Url).ToList();
			SelectControl sourcefroms = new SelectControl() { ButtonValue = "请选择来源", ControlType = HtmlControlType.radio, Text = "Name", Value = "SourceFromID", SelectedValues = selectSourceFrom, EnumerableData = sourceFromList, ExtendAttributes=extendAttributes, Title = "请选择来源", CallbackScriptFunction = "setSourceFrom", PageControlID = 1 };
			ViewData["SourceFrom"] = sourcefroms;
			SelectControl characters = new SelectControl() { ButtonValue = "请选择主演", ControlType = HtmlControlType.checkbox, Text = "StarName", Value = "StarID", SelectedValues= selectStars, EnumerableData = stars, Title = "请选择主演", CallbackScriptFunction = "setStar", PageControlID = 2 };
			ViewData["Star"] = characters;
			SelectControl directors = new SelectControl() { ButtonValue = "请选择导演", ControlType = HtmlControlType.radio, Text = "StarName", Value = "StarID", SelectedValues=selectDirector, EnumerableData = stars, Title = "请选择导演", CallbackScriptFunction = "setDirector", PageControlID = 3 };
			ViewData["Director"] = directors;
		}

		//
		// POST: /AdminVideo/Create

		[AcceptVerbs(HttpVerbs.Post)]
		[ValidateInput(false)]
		public ActionResult Create(string tags, string castCharacters, int? previewYear, Video video, HttpPostedFileBase coverImage)
		{
			DateTime previewTime = new DateTime(previewYear ?? DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day);
			video.PreviewTime = previewTime;
			video.AddTime = DateTime.Now;
			video.IsGroup = false;
			video.IsPublished = (int)EnumPublishState.未发布;
			int videoId=bizVideo.Insert(tags, castCharacters, video);
			video.CoverImagePath = SaveImage(coverImage, videoId);
			bizVideo.Update(video);
			return RedirectToAction("Index", new { categoryid=video.CategoryID});
		}

		//
		// GET: /AdminVideo/Edit/5

		public ActionResult Edit(int id)
		{
			ViewData["Title"] = "视频编辑";
			Video video = bizVideo.Get(id);
			//tags
			ViewData["Tags"]=bizVideoXTag.ListVideoTagsByString(id);
			//video 来源
			List<string> selectSourceFrom = new List<string>() { video.SourceFromID.ToString() };
			//video 导演
			List<string> selectDirector = new List<string>();
			if (video.Director != null)
				selectDirector.Add(video.Director.ToString());
			//video 主演
			List<string> characters = bizCastCharacter.ListVideoCastCharacters(id).Select(x=>x.StarID.ToString()).ToList();
			//上映年份
			ViewData["previewYear"] = video.PreviewTime == null ? "" : video.PreviewTime.Value.Year.ToString();
			ViewData["CategoryName"] = bizVideoCategory.Get(video.CategoryID ?? 0).Name;
			ViewData["CategoryID"] = video.CategoryID;
			InitCreateUpdate(selectSourceFrom,characters,selectDirector);
			return View("Create",video);
		}

		//
		// POST: /AdminVideo/Edit/5

		[AcceptVerbs(HttpVerbs.Post)]
		[ValidateInput(false)]
		public ActionResult Edit(int? id, string tags, string castCharacters, int? previewYear, HttpPostedFileBase coverImage,Video video)
		{
			DateTime previewTime = new DateTime(previewYear ?? DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day);
			video.PreviewTime = previewTime;
			video.VideoID = id ?? 0;
			video.CoverImagePath=SaveImage(coverImage, id.Value);

			bizVideo.Update(tags, castCharacters, video);
			TempData["UpdateResult"] = "更新成功";

			return RedirectToAction("Edit", new { id = id });
		}

		[AcceptVerbs(HttpVerbs.Post)]
		public bool Delete(int? id)
		{
			return bizVideo.Delete(id ?? 0);
		}

		[AcceptVerbs(HttpVerbs.Post)]
		public bool DeleteInList(int? id)
		{
			bizVideo.Update(id ?? 0, x => new Video() { DefineType=(int)EnumDefineType.None });
			return true;
		}

		public ActionResult ListVideoList(int? pageNo, SearchVideoList searchObj)
		{
			int totalCount;
			if (searchObj.IsPublished == EnumPublishState.全部)
				searchObj.IsPublished = null;
			if (searchObj.VideoCategroyId == -1)
				searchObj.VideoCategroyId = null;
			ViewData["VideoList"] = bizVideoList.List(searchObj, pageNo ?? 0, PAGE_SIZE, out totalCount);
			ViewData["PaginateHelper"] = PaginateHelper.ConstructPaginate(totalCount, pageNo ?? 0, PAGE_SIZE, "/AdminVideo/ListVideoList/", searchObj);
			return View();
		}

		public ActionResult SetVideoList(int id,string retUrl)
		{
			VideoList[] videoList=bizVideoList.List(id);
			Video video = bizVideo.Get(id);
			ViewData["VideoList"] = videoList;
			ViewData["Video"] = video;
			ViewData["RetUrl"] = retUrl;
			return View();
		}

		[AcceptVerbs(HttpVerbs.Post)]
		public ActionResult SetVideoList(int id,EnumVideoListType listType)
		{
			Video video = bizVideo.Get(id);
			VideoList vl = new VideoList() { 
				IsPublished=(int)EnumPublishState.发布,
				ListType=(int)listType,
				VideoID=id,
				CoverImageSrc=video.CoverImagePath.Substring(24),
				 AddTime=DateTime.Now
			};
			bizVideoList.Insert(vl);
			return Content(Convert.ToString((int)EnumOperateState.成功));
		}

		public ActionResult EditSingleVideoList(int id, EnumVideoListType listType)
		{
			Video video = bizVideo.Get(id);
			ViewData["Video"] = video;
			return View();
		}

		[AcceptVerbs(HttpVerbs.Post)]
		public ActionResult EditSingleVideoList(int id, EnumVideoListType listType, string txt_width, string txt_height, string txt_top, string txt_left, string txt_DropWidth, string txt_DropHeight)
		{
			int imageWidth = Int32.Parse(txt_width);
			int imageHeight = Int32.Parse(txt_height);
			int cutTop = Int32.Parse(txt_top);
			int cutLeft = (int)double.Parse(txt_left);
			int dropWidth = Int32.Parse(txt_DropWidth);
			int dropHeight = Int32.Parse(txt_DropHeight);
			Video video = bizVideo.Get(id);
			string folder = "";
			switch (listType)
			{
				case EnumVideoListType.推荐视频:
					break;
				case EnumVideoListType.大网站焦点视频:
					break;
				case EnumVideoListType.首页焦点视频:
					folder = Hotnet.Biz.Properties.Settings.Default.首页焦点视频文件夹;
					break;
				case EnumVideoListType.分类焦点视频:
					break;
				default:
					break;
			}
			VideoList vl = new VideoList();
			vl.VideoID = video.VideoID;
			vl.IsPublished = (int)EnumPublishState.发布;
			vl.ListType = (int)listType;
			vl.AddTime = DateTime.Now;

			if (listType == EnumVideoListType.首页焦点视频)
			{
				string imageName = null;
				string dir = StringUtility.GetSavePath(id, out imageName);
				string LocalPath = dir + imageName + "_o" + Path.GetExtension(video.CoverImagePath);

				string filename = CutPhotoHelp.SaveCutPic(Server.MapPath(video.CoverImagePath), Server.MapPath(folder + LocalPath), 0, 0, dropWidth,
										dropHeight, cutLeft, cutTop, imageWidth, imageHeight);
				vl.CoverImageSrc = LocalPath;
			}
			bizVideoList.Delete(vl.VideoID, listType);
			bizVideoList.Insert(vl);

			return RedirectToAction("SetVideoList", new { id = video.VideoID, listType = (int)listType });
		}

		[AcceptVerbs( HttpVerbs.Post)]
		public void SetVideoListPublished(int id, EnumVideoListType listType, int publishedState)
		{
			bizVideoList.Update(x => x.VideoID == id && x.ListType == (int)listType, x => new VideoList() { IsPublished = publishedState });
		}

		[AcceptVerbs(HttpVerbs.Post)]
		public void DeleteVideoList(int id, EnumVideoListType listType)
		{
			bizVideoList.Delete(id,listType);
		}


		

		[AcceptVerbs(HttpVerbs.Post)]
		public void SetPublished(int videoID)
		{
			bizVideo.Update(videoID, x => new Video() { IsPublished = 1 });
		}

		[AcceptVerbs(HttpVerbs.Post)]
		public void UnSetPublished(int videoID)
		{
			bizVideo.Update(videoID, x => new Video() { IsPublished = 0 });
		}

		public static SelectList PreviewTimeList
		{
			get
			{
				int nowYear = DateTime.Now.Year;
				List<SelectListItem> items = new List<SelectListItem>();
				SelectListItem firstItem = new SelectListItem();
				firstItem.Value = "";
				firstItem.Text = "请选择年份..";
				items.Insert(0, firstItem);
				for (int i = nowYear; i >= nowYear - 30; i--)
				{
					SelectListItem item = new SelectListItem();
					item.Text = i.ToString();
					item.Value = i.ToString();
					items.Add(item);
				}
				return new SelectList(items, "Value", "Text");
			}
		}

		public static SelectList VideoNetList
		{
			get
			{
				BizSourceFrom s = new BizSourceFrom();
				List<SourceFrom> list=s.List(EnumSystemCategory.视频).ToList();
				SourceFrom temp=new SourceFrom();
				temp.SourceFromID=-1;
				temp.Name="全部";
				list.Insert(0,temp);
				return new SelectList(list,"SourceFromID","Name");
			}
		}

		public static SelectList VideoCategroyList
		{
			get
			{
				BizVideoCategory p = new BizVideoCategory();
				List<VideoCategory> list = p.List().ToList();
				VideoCategory temp = new VideoCategory();
				temp.CategoryID = -1;
				temp.Name = "全部";
				list.Insert(0, temp);
				return new SelectList(list, "CategoryID", "Name");
			}
		}


		private string SaveImage(HttpPostedFileBase coverImage, int videoId)
		{
			if (coverImage == null || videoId == 0)
				return null;
			string fileName;
			string fileExtension = coverImage.FileName.Substring(coverImage.FileName.IndexOf("."));
			string savePath = StringUtility.GetSavePath(videoId, out fileName);
			string dirPath = AppDomain.CurrentDomain.BaseDirectory + videoCoverImageFolder + savePath;
			if (!Directory.Exists(dirPath))
				Directory.CreateDirectory(dirPath);
			savePath = videoCoverImageFolder + savePath + fileName + fileExtension;
			coverImage.SaveAs(AppDomain.CurrentDomain.BaseDirectory + savePath);
			return savePath;
		}

		public static string GetVideoListImageSrc(VideoList videolist)
		{
			EnumVideoListType listType = (EnumVideoListType)videolist.ListType;
			switch (listType)
			{
				case EnumVideoListType.推荐视频:
				case EnumVideoListType.大网站焦点视频:
				case EnumVideoListType.分类焦点视频:
					return Biz.Properties.Settings.Default.VideoCoverImageFolder + videolist.CoverImageSrc;
				case EnumVideoListType.首页焦点视频:
					return Biz.Properties.Settings.Default.首页焦点视频文件夹 + videolist.CoverImageSrc;
				default:
					break;
			}
			return "";
		}


	}
}
